/**
 * @Author: 陈瑞鹏
 * @Date:   2022-11-01 16:15:41
 * @Last Modified by:   陈瑞鹏
 * @Last Modified time: 2023-11-30 19:03:22
 */
import socketIo from "socket.io";
import MUser from "../../miniGames/mUser.model";
import Redis from "../redis";
import room from "./room";

export default class socket {
  io: socketIo.Server;
  port: number; //端口
  static enterGameNamesape: socketIo.Namespace;
  static socketData: any;
  static downTimeHandlerArr: any = [];
  constructor(port: number) {
    console.log(port, 'riq');

    this.io = socketIo.listen(port);
    this.port = port;
  }

  /**
   * 加入房间
   * @param roomId 
   */
  onterRoom() {
    this.io.of(`/`).on('connection', async (socketData: any) => {
      const namespace: socketIo.Namespace = socketData.nsp;
      socket.enterGameNamesape = namespace;
      socket.socketData = socketData;
      let { transport, roleId, roomId } = socketData.handshake.query;
      if (transport != 'websocket') {
        return;
      }
      let userInfo: any = await MUser.findOne({ roleId });
      if (!userInfo) return;

      let toSid = userInfo.sid;
      if (userInfo.isOnline || socketData.id != toSid || toSid != "") {
        await MUser.updateOne({ roleId }, { isOnline: false, sid: "" });
      }

      await MUser.updateOne({ roleId }, { isOnline: true, sid: socketData.id });
      await room.join_room(userInfo, roomId, socketData.id);

      socketData.on("disconnect", async () => {
        await MUser.updateOne({ roleId }, { isOnline: false, sid: "" });
        await room.leave_room(userInfo, roomId);
      })

      socketData.on("disMiss", async () => {
        await room.disMiss_room(roomId);
      })

      socketData.on("gameReady", async (res) => {
        console.log(res);
        await room.game_ready(userInfo, roomId);
      })

      socketData.on("gameStart", async (res) => {
        // console.log(res);
        await room.game_start(roomId);
      })

      socketData.on("gameDataUpdate", async (res) => {

        await Redis.hset(res.roomId, res.roleId, res.money);

        room.send_room_msg("gameDataUpdate", { message: `数据修改`, upData: res }, "room_" + res.roomId);

      })

      socketData.on("drawStart", async (res) => {
        await room.draw_start(roomId);
      })

      socketData.on("drawEnd", async (res) => {
        await room.draw_end(roomId);
      })
    })
  }
}